package cn.sise.edu.crm.web.controller;

import cn.sise.edu.crm.domain.Department;
import cn.sise.edu.crm.domain.JsonResult;
import cn.sise.edu.crm.query.QueryObject;
import cn.sise.edu.crm.service.IDepartmentService;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by chen on 2019/11/3.
 */
@Controller
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    @RequestMapping("/list")
    @RequiresPermissions(value = {"部门页面", "department:list"},logical = Logical.OR)
    public String list(Model model, @ModelAttribute("qo") QueryObject qo) {
       // int i =1/0;
        PageInfo<Department> pageInfo = departmentService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "department/list";
    }

    @RequestMapping("/input")
    public String input(Long id, Model model) {
        if (id != null) {

            Department department = departmentService.selectById(id);
            model.addAttribute("department", department);
            return "/department/input";
        } else {
            return "/department/input";
        }
    }
    @RequestMapping("/delete")
    @ResponseBody
    @RequiresPermissions(value = {"部门删除", "department:delete"},logical = Logical.OR)
    public JsonResult delete(Long id){
        try {
            departmentService.delete(id);
        } catch (Exception e) {
            return new JsonResult("删除失败",false);
        }
        return new JsonResult("删除成功",true);
    }
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    @RequiresPermissions(value = {"部门增加或更新", "department:saveOrUpdate"},logical = Logical.OR)
    public JsonResult saveOrUpdate(Department department){
        try {
            if(department.getId() != null){

                departmentService.update(department);
            }else{
                departmentService.insert(department);
            }
        }catch (Exception e){
           return new JsonResult("保存或者更新失败",false);
        }

        return  new JsonResult("保存或者更新成功",true);
}
}
